/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-05-21
 * Time: 16:21
 */
public class Main {
    public int monotoneIncreasingDigits(int n) {
        int i = 0;
        //1.将n转化为字符数组
        char[] s = Integer.toString(n).toCharArray();
        //2.遍历字符数组s
        int len = s.length;
        while(i+1 < len && s[i] <= s[i+1]) {
            i++;
        }
        //3.说明找到出现单调递减的位置

        //3.1该位置之后没有元素，则直接返回
        if(i == len-1) {
            return n;
        }
        //3.2如果s[i-1] == s[i]则需要回退，不满足则直接跳过执行3.3
        while(i-1 >= 0 && s[i-1] == s[i]) {
            i--;
        }
        //3.3最后确定的位置减1
        s[i]--;
        //3.4最后确定位置的后面全改为字符9
        for(int j = i+1; j < len; j++) {
            s[j] = '9';
        }
        //4.将字符s转化为数字并返回
        return Integer.parseInt(new String(s));

    }
}
